// Remove User From Group Controller
// Remove a user from a group

function UserFromGroupRemover(userName, groupName) {

    function findGroupAndRemoveUser() {    
        var group = groups.getGroup(groupName);
        if (group !== null) {
            return removeUser(group);  
        } else {
            return groupNotFound();
        }        
    }

    function findUser(removeWhenFound) {
        var user = people.getPerson(userName);
        if (user === null) {
            return userNotFound();
        } else {
            return removeWhenFound(user);
        }
    }

    function groupNotFound() {
        return {success: false,
                message: "Group not found: " + groupName};
    }

    function userNotFound() {
        return {success: false,
                message: "User not found: " + userName};
    }

    function removeUser(group) {
        function removeWhenFound(user) {
            return removeUserFromGroup(user, group);
        }
        return findUser(removeWhenFound);
    }

    function removeUserFromGroup(user, group) {
         try {
            group.removeAuthority(userName);
         } catch (ex) {
            return {success: false, message: "Error removing user: " + ex};
         }            
         return {success: true,
                 message: "User removed from group"};
    }

    function remove() {
         return findGroupAndRemoveUser(); 
    }

    return {
        remove: remove
    }

}

function removeUserFromGroup(userName, groupName) {

    var remover = UserFromGroupRemover(userName, groupName);
    return remover.remove();

}

var groupName = args.groupName;
var userName = args.userName;

var result = removeUserFromGroup(userName, groupName);
model.message = jsonUtils.toJSONString(result);

